package gold.digger;

import gold.utils.InputUtil;

import java.util.*;
import java.util.List;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC795 {
    public long startExecuteTime = System.currentTimeMillis();


    /*
     * @param 此题目参考了别人代码
     * 这是因为问题情况较为复杂
     * 未来需要再次复习此道题目
     * 我擦题解是真的秀，我是实在不想debug了，浪费时间，及时止损
     * @return:
     */
    class Solution {
        public int numSubarrayBoundedMax(int[] A, int L, int R) {
            return count(A, R) - count(A, L - 1);
        }

        public int count(int[] A, int bound) {
            int ans = 0, cur = 0;
            for (int x : A) {
                cur = x <= bound ? cur + 1 : 0;
                ans += cur;
            }
            return ans;
        }
    }


    class Solution_Fail_Execute {
        public int numSubarrayBoundedMax(int[] A, int L, int R) {
            PriorityQueue<Integer> queue = new PriorityQueue<>(Collections.reverseOrder());
            int curSize = 0, left = 0, right = 0, count = 0;
            while (right < A.length) {
                queue.offer(A[right++]);
                if (!(queue.peek() <= R && queue.peek() >= L)) {
                    queue.remove(A[right - 1]);
                    while (!queue.isEmpty() && left < right - 1) {
                        if (queue.peek() <= R && queue.peek() >= L) count += queue.size();
                        queue.remove(A[left++]);
                    }
                    left = right;
                }
            }

            curSize = queue.size();
            count += (curSize + 1) * (curSize) / 2;
            return count;
        }
    }

    public void run() {
        Solution solution = new Solution();
        int[] arr = InputUtil.toIntegerArray("[2, 1, 4, 3]");
        System.out.println(solution.numSubarrayBoundedMax(arr, 2, 3));
    }

    public static void main(String[] args) throws Exception {
        LC795 an = new LC795();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
